package org.grow.shawatch.controller;

import org.grow.shawatch.entity.DebugLogDto;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 2021/12/28
 */

@RestController
public class LogPresentController {


    @PostMapping("/reduceLogs")
    public List<String> reduceLog() {
        String dir = System.getProperty("user.home");
        Path t = Paths.get(dir).resolve("document/sgsReduce");
        if (Files.notExists(t)) {
            throw new RuntimeException("目标文件不存在");
        }
        List<String> contents = null;
        try {
            contents = Files.readAllLines(t);
        } catch (IOException e) {
            contents.add("抱歉文件读写出错了");
        }
        return contents;
    }

    @PostMapping("/debugLogs")
    public List<String> debugLog(@RequestBody DebugLogDto debugLogDto) {
        Integer startLine = debugLogDto.getStartLine();
        Integer currentLine = 1;
        List<String> results = new LinkedList<>();
        String dir = System.getProperty("user.home");
        Path t = Paths.get(dir).resolve("document/sgs.txt");
        if (Files.notExists(t)) {
            throw new RuntimeException("目标文件不存在");
        }
        BufferedReader bufferedReader = null;

        try {
            bufferedReader = Files.newBufferedReader(t, StandardCharsets.UTF_8);
            String content;
            while ((content = bufferedReader.readLine()) != null) {
                currentLine++;
                if (currentLine >= startLine) {
                    results.add(content);
                }
            }
        } catch (IOException e) {
            System.out.println(t + "文件读写出错");
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ;
            return results;
        }

    }
}
